<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\Cola\Service;

use App\Cola\Mapper\ColaBillMapper;
use App\Cola\Model\ColaBill;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

/**
 * 账本记录服务类
 */
class ColaBillService extends AbstractService
{


    /**
     * @var ColaBill
     */
    #[Inject]
    protected ColaBill $model;

    public function __construct(ColaBillMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * @var ColaLedgerService
     */
    #[Inject]
    protected ColaLedgerService $ledgerService;


    /**
     * 新增
     * */
    public function addService(array $params): bool
    {
        return Db::transaction(function () use ($params) {
            $ledger_id = $params['ledger_id'];
            unset($params['ledger_id']);

            $params['trade_status'] = '交易成功';
            $bill_id = $this->model::insertGetId($params);

            if (!$bill_id) {
                $this->logger->error('[账单详情]插入失败', ['params' => $params]);
                throw new NormalStatusException('插入失败');
            }

            $this->ledgerService->JoinBillService($params['user_id'], $ledger_id, $bill_id);

            logger()->info('[账单详情]插入成功', ['params' => $params]);
            return true;
        });
    }


    /**
     * 获取列表
     * */
    public function getApiList($params, $field = ['*'], $page = 1, $size = 20)
    {
        $query = ColaBill::query()->select($field);

        $query->whereHas('ledgers',function ($q)use($params){
            $q->where('cola_ledger_id',$params['ledger_id']);
        });
        // 条件处理
        $this->addCondition($query, 'user_id', $params);
        $this->addCondition($query, 'pay_source', $params);
        $this->addCondition($query, 'trade_cate_id', $params);
        $this->addCondition($query, 'counterparty', $params, true);
        $this->addCondition($query, 'counterparty_account', $params, true);
        $this->addCondition($query, 'goods', $params, true);
        $this->addCondition($query, 'cash_flow', $params);
        $this->addCondition($query, 'payment_method', $params);
        $this->addCondition($query, 'trade_status', $params, true);
        $this->addCondition($query, 'trade_sn', $params);
        $this->addCondition($query, 'trade_store_sn', $params);
        $this->addAmountCondition($query, 'money', $params);
        $this->addDateCondition($query, 'pay_time', $params);
        $this->addDateCondition($query, 'created_at', $params);

        $count_query = clone $query;
        $list_query = clone $query;

        $count = $count_query->count();
        $list = $list_query->offset(($page - 1) * $size)
            ->limit($size)
            ->orderByDesc('pay_time')
            ->get();

        return ['count' => $count, 'list' => $list];
    }

    private function addCondition($query, $field, $params, $like = false)
    {
        if (!empty($params[$field])) {
            if ($like) {
                $query->where($field, 'like', '%' . $params[$field] . '%');
            } else {
                $query->where($field, $params[$field]);
            }
        }
    }

    private function addDateCondition($query, $field, $params)
    {
        if (!empty($params[$field])) {
            $query->whereDate($field, $params[$field]);
        }
        if (!empty($params[$field . '_start']) && !empty($params[$field . '_end'])) {
            $query->whereBetween($field, [$params[$field . '_start'], $params[$field . '_end']]);
        }
    }

    private function addAmountCondition($query, $field, $params)
    {
        if (!empty($params[$field])) {
            $query->where($field, $params[$field]);
        }
        if (!empty($params[$field . '_min']) && !empty($params[$field . '_max'])) {
            $query->whereBetween($field, [$params[$field . '_min'], $params[$field . '_max']]);
        }
    }



}